<template>
  <div class="page-warp h-f bg-grey-200" :style="CC_PAGE_STYLE">
    <div class="header-warp">
      <div class="sticky-headers bg-white">
        <div class="form-warp bg-white" ref="headerForm">
          <uni-forms
            class-name="borderless"
            label-width="120px"
            label-align="left"
            :modelValue="form"
            :rules="formRules"
            ref="formRef"
          >
            <uni-forms-item label="盘点单号" name="ivoCode">
              <uni-easyinput v-model="form['ivoCode']"
                             :placeholder="b_PLACEHOLDER_STR('', COM_TYPE.GEN)"
                             :disabled="true"></uni-easyinput>
            </uni-forms-item>
            <uni-forms-item label="盘点日期" name="ivoDate" required>
              <uni-datetime-picker type="datetime"
                                   :placeholder="b_PLACEHOLDER_STR('入库日期', COM_TYPE.SELECT)"
                                   v-model="form['ivoDate']"
                                   :disabled="isview"
              ></uni-datetime-picker>
            </uni-forms-item>
            <uni-forms-item label="盘点部门" name="ivoOrgId" required>
              <input-item-selector
                event-id="dept"
                page="/pages/dialogs/DeptDialog"
                value-key="F_DepartmentId"
                label-key="F_FullName"
                :placeholder-selector="b_PLACEHOLDER_STR('盘点部门', COM_TYPE.SELECT)"
                :display-value="form['ivoOrgName']"
                v-model="form['ivoOrgId']"
                @change="deptChange"
                :disabled="isview"
              ></input-item-selector>
            </uni-forms-item>

            <uni-forms-item label="盘点仓库" name="bwaId" required>
              <uni-data-select
                :localdata="bwaData.rows"
                v-model="form['bwaId']"
                :placeholder="b_PLACEHOLDER_STR('盘点仓库', COM_TYPE.SELECT)"
                valueKey="bwa_id"
                labelKey="bwa_name"
                @select="bwaChange($event,row,index)"
                :disabled="true"
              />
            </uni-forms-item>

            <uni-forms-item label="盘点人员" name="ivoPersonName" required>
              <input-item-selector
                event-id="user-select-dialog"
                page="/pages/dialogs/UserDialog"
                value-key="F_UserId"
                label-key="F_RealName"
                :placeholder-selector="b_PLACEHOLDER_STR('盘点人员', COM_TYPE.SELECT)"
                :display-value="form['ivoPersonName']"
                v-model="form['ivoPersonId']"
                @change="userChange"
                :disabled="isview"
              ></input-item-selector>
            </uni-forms-item>
            <uni-forms-item label="备注" name="remark">
              <uni-easyinput v-model="form['remark']"
                             :placeholder="b_PLACEHOLDER_STR('备注', COM_TYPE.IN)"
                             :disabled="isview"
              />
            </uni-forms-item>
          </uni-forms>
        </div>
      </div>
    </div>

    <div class="f-warp">
      <div class="fillet">
        <span class="fillet__text">单据明细</span>
        <span class="flex">
          <button-circle
            type="primary"
            @click="addbii"
            v-if="!isview && !isadjust"
          >
            增行
          </button-circle>
          <button-circle
            type="primary"
            @click="addItem"
            v-if="!isview && !isadjust"
          >
            库存快照
          </button-circle>
        </span>
      </div>
      <div class="form-warp bg-grey-200">
        <stock-item-list
          :data="list.rows"
          @delete="itemDelete"
          :columns="list.columns"
        >
          <template #bwl_name="{row,index}">
            <uni-data-select
              :localdata="bwlData.rows"
              v-model="row['bwl_id']"
              :placeholder="b_PLACEHOLDER_STR('库位', COM_TYPE.SELECT)"
              valueKey="bwl_id"
              labelKey="bwl_name"
              @select="bwlChange($event,row,index)"
              :disabled="isview || row['bwl_disabled'] || isadjust"
            />
          </template>

          <template #verQty="{row}">
            <uni-easyinput v-model="row['verQty']"
                           :placeholder="b_PLACEHOLDER_STR('盘点数量', COM_TYPE.IN)"
                           type="number"
                           :disabled="!canVerQty(row)"
            />
          </template>
          <template #menu="{ row, index }">
            <div class="btn-rows">
              <button-circle
                type="danger"
                size="mini"
                @click="itemDelete(row, index)"
                v-if="!isview && !isadjust"
                >删除
              </button-circle>
            </div>
          </template>
        </stock-item-list>
      </div>
    </div>

    <div class="form-footer">
      <div class="footer-warp">
        <div class="footer__btn">
          <div class="btn">
            <button class="uni-btn"
                    @click="cancel"
                    :disabled="loadingStore.ILOADING"
            >
              取消
            </button>
          </div>
          <div class="btn"     v-if="!isview && !isadjust">
            <button class="uni-btn"
                    type="primary"
                    @click="confirm(0)"
                    :disabled="loadingStore.ILOADING"
                    :loading="loadingStore.ILOADING"
            >
              暂存
            </button>
          </div>
          <div class="btn"
               v-if="!isview">
            <button class="uni-btn"
                    type="primary"
                    @click="confirm(1)"
                    :disabled="loadingStore.ILOADING"
                    :loading="loadingStore.ILOADING"
            >
              {{ isadjust ? '提交' : '保存' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <uni-message-ex custom-nav />

    <input-item-selector
      dialog-only
      multiple
      ref="biiRef"
      event-id="bii-select-dialog"
      page="../../../dialogs/BiiDialog"
      value-key="bii_id"
      label-key="bii_name"
      @change="biiChange"

    ></input-item-selector>


    <ConfirmModal
      v-model="dialog.adj.show"
      :message="dialog.adj.msg"
      @change="onConfirm"
    />
  </div>

</template>

<script setup>
import { computed, reactive, ref } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { usePageParamHook } from '../../material/common/PageParam'
import { useStaticTypeDictionaries } from '../../../../components/StaticDictionary/StaticTypeDictionaries'
import { useLoading } from '../../../../store/LoadingStore'
import { useMessage } from '../../../../store/MessageStore'
import { usePageHeaderForm } from '../../../../hooks/PageHeaderForm'
import { PageUtil } from '../../../../utils/PageUtil'
import InputItemSelector from '../../../../components/InputItemSelector.vue'
import UniMessageEx from '../../../../components/UniMessageEx.vue'
import StockItemList from '../../../../components/StockItem/StockItemList.vue'
import ButtonCircle from '../../../../components/ButtonCircle.vue'
import { useFormServ } from '../../../../hooks/FormServ'
import { useDictionaryStore } from '../../../../store/DictionaryStore'
import { useStockResStore } from '../../../../store/StockResulting'
import { StringUtils } from '../../../../utils/StringUtils'
import { ObjectArray } from '../../../../utils/convertable/ObjectArray'
import { CONVERT_TYPE } from '../../../../utils/convertable/Consts'
import ConfirmModal from '../../../../components/ConfirmModel/ConfirmModal.vue'
import moment, { Ls } from 'dayjs'

//#region Refs
const headerForm = ref(null)
const formRef = ref(null)
const biiDialog = ref(null)

//#endregion Refs


//#region Const


//#endregion Const

//#region Use
const {
  setupPage
} = usePageParamHook()
const {
  COM_TYPE,
  b_PLACEHOLDER_STR
} = useFormServ()

const {
  KEYS,
  O2A
} = useStaticTypeDictionaries()
const loadingStore = useLoading()
const stockResStore = useStockResStore()
const msgStore = useMessage()
const dictStore = useDictionaryStore()
const { CC_PAGE_STYLE } = usePageHeaderForm(headerForm)
//#endregion Use


//#region Data
const pageParams = ref({})
const form = reactive({})
const formRules = ref({
  iioApplyDate: {
    rules: [{
      required: true,
      errorMessage: ' '
    }]
  },
  iioBussTypeCode: {
    rules: [{
      required: true,
      errorMessage: ' '
    }]
  },
  iioBussTypeTwoCode: {
    rules: [{
      required: true,
      errorMessage: ' '
    }]
  },
  iioBussCode: {
    rules: [{
      required: true,
      errorMessage: ' '
    }]
  },
  iioOrgId: {
    rules: [{
      required: true,
      errorMessage: ' '
    }]
  },
  iioBussManName: {
    rules: [{
      required: true,
      errorMessage: ' '
    }]
  }
})
const list = reactive({
  rows: [],
  total: 0,
  columns: [
    { label: '存货编号', prop: 'bii_code' },
    { label: '存货名称', prop: 'bii_name' },
    { label: '规格型号', prop: 'bii_spec' },
    { label: '库位', prop: 'bwl_name' ,slot:true},
    { label: '库存量', prop: 'isiQty' },
    { label: '盘点数量', prop: 'verQty', slot: true },
    { label: '批次', prop: 'batch' },
    { label: '备注', prop: 'remark' }
  ]
})
const bwlData = reactive({
  rows: []
})

const isview = computed(() => {
  const { __view = false } = pageParams.value
  return __view
})

const isadjust = computed(() => {
  const { __adjust = false } = pageParams.value
  return __adjust
})
//#endregion Data

//#region Method
const queryData = function() {
  dictStore.getBwaList({
    limit: -1,
    size: -1,
    bwa_state: 1
  }).then(res => {
    const { Rows = [] } = res || {}
    bwaData.rows = Rows
  })

  const { ivoId: id,bwaId } = form

  dictStore.getBwlList({
    limit: -1,
    size: -1,
    bwl_state: 1,
    bwa_id:bwaId
  }).then(res => {
    const { Rows = [] } = res || {}
    bwlData.rows = Rows
  })

  if (!StringUtils.isEmptyOrNull(id)) {
    stockResStore.getDetail({
      id
    }).then(res => {
      const { bodyList = [] } = res || {}
      Object.entries(res).forEach(([key, value]) => {
        form[key] = value
      })
      console.log(form)
      const rows = new ObjectArray(bodyList)
        .setType(CONVERT_TYPE.S)
        .excludeTypeKey([
          'isiQty',
          'verQty'
        ])
        .build()
        .map(item => {
          return {
            ...item
          }
        })
      // 盘点----只有增行新增的物料可以编辑库位
      const { __check = false } = pageParams.value
      if(__check){
        rows.map(x=>{
          x.bwl_disabled = true;
        })
      }
      list.rows = rows
    })
  }
}

const biiChange = function(rows) {
  const _rows = rows || []
  const ex = list.rows.map(x => x["bii_id"])
  _rows.map((row) => {
    if (ex.includes(row["bii_id"])) {
      return
    }
    const bii = {
      bii_code: row["bii_code"],
      bii_name: row["bii_name"],
      bu_id: row["bu_id"],
      bu_name: row["bu_name"],
      bii_id: row["bii_id"],
      bii_spec: row["bii_spec"],
      amount: row["amount"],
      qty: row["qty"],
      stock_qty: row["stock_qty"],
      price: row["price"],
      pob_id: row["pob_id"],
      isiQty: 0,
      batch: [
        row["bii_code"],
        moment().format('YYYYMMDD')
      ].join(''),
      __custom: true
    }
    list.rows.push(bii)
  })
}

const userChange = function(row) {
  const [item] = row || {}
  const { F_UserId, F_RealName } = item
  form['iioBussManId'] = F_UserId
  form['iioBussManName'] = F_RealName
}

const canVerQty = function(row) {
  let result = true;
  const { __view = false,__check = false } = pageParams.value
  if(__view) {
    result = false
  }else if(__check){
  }else{
    if(row['__custom']){
      result = true
    }else{
      result = false
    }
  }
  return result
}

const deptChange = function(row) {
  const [item] = row || {}
  const { F_DepartmentId, F_FullName } = item
  form['iioOrgName'] = F_FullName
  form['iioOrgId'] = F_DepartmentId
}


const bwaData = reactive({
  rows: []
})
const bwaChange = function(e,row,index) {
  const { bwa_id, bwa_name,bwa_code } = e
  form.bwaId = bwa_id
  form.bwaName = bwa_name
  form.bwaCode = bwa_code

  dictStore.getBwlList({
    limit: -1,
    size: -1,
    bwl_state: 1,
    bwa_id
  }).then(res => {
    const { Rows = [] } = res || {}
    bwlData.rows = Rows
  })
}

const bwlChange = function(e,row,index) {
  list.rows[index].bwl_name = e['bwl_name']
  list.rows[index].bwl_code = e['bwl_code']
}


const addItem = function() {


  const { bwaId: bwa_id } = form
  if(StringUtils.isEmptyOrNull(bwa_id)){
    msgStore.error('请选择盘点仓库')
    return
  }

  loadingStore.SET_LOADING()
  stockResStore.getStorageSnapshot({
    bwa_id
  }).then((res) => {
    list.rows = res
    loadingStore.FINISH_ALL()
  })
}

const biiRef = ref(null)
const addbii = function(){
  biiRef.value.show()
}

const itemDelete = function(row, index) {
  list.rows.splice(index, 1)
}

const cancel = function() {
  PageUtil.back()
}

const dialog = reactive({
  adj: {
    show: false,
    msg: '确定要调账吗?'
  }
})

const onConfirm = function(e) {
  if (!e) return
  const { ivoId } = form
  stockResStore.adjustAccount({
    ivoId
  }).then(res=>{
    const { success, msg} = res
    if (success) {
      msgStore.success('调账成功')
      PageUtil.back()
    }else{
      msgStore.error(msg)
    }
  })
}

const confirm = function(sts) {
  if(isadjust.value){
    dialog.adj.show = true
    return
  }

  const errors = []
  list.rows.map(x=>{
    if(!x.bwl_id){
      msgStore.error('请选择库位!')
      errors.push(x)
    }
  })
  if(errors.length){
    return
  }

  let bodyList = list.rows.map(x => {
    return {
      ...x
    }
  })
  let params = {
    ...form,
    bodyList: new ObjectArray(bodyList).setType(CONVERT_TYPE.C).build(),
    ivoState: sts
  }
  console.log('parms--',params)
  formRef.value.validate().then(() => {
    if (!list.rows.length) {
      msgStore.error('暂无物料信息!')
      return
    }
    const { ivoId: id } = params || {}
    const act = StringUtils.isEmptyOrNull(id) ? 1 : 2
    loadingStore.SET_LOADING()
    stockResStore.listMod({
      act,
      id,
      form:{
        ...params
      },
    }).then(res => {
      const { msg, success } = res
      if (success) {
        msgStore.success('保存成功')
        PageUtil.back()
        loadingStore.FINISH_ALL()
        return
      }
      msgStore.error(msg)
      loadingStore.FINISH_ALL()
      // PageUtil.back()
    }).catch(() => {
      loadingStore.FINISH_ALL()
    })
  })

}
//#endregion Method


//#region Page Events
onLoad((params) => {
  let _p = PageUtil.parseParam(params)
  let { row: p } = _p
  Object.entries(p).forEach(([key, value]) => {
    form[key] = value
    pageParams.value[key] = value
  })

  queryData()

})

onReachBottom(() => {
  console.log('bottom')
})
//#endregion Page Events

</script>

<style lang="scss" scoped>
@import "@/assets/PageCommon.scss";
@import "@/assets/PageHeaderForm.scss";


.page-warp {
  .header-warp {
    &:after {
      height: 0px;
    }
    .form-warp {
      padding: 0 12px;
      padding-right: 0;
    }
  }


  .fillet {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .f-warp {
    .form-warp {
      padding-bottom: 12px;
    }
  }

  .form-footer {
    height: 60px;
  }
}

.ct-end {
  display: flex;
  justify-content: flex-end;
  margin-right: 12px;

  .len-md {
    min-width: 20%;

    .ct-btn {
      width: 100%;
    }
  }
}

::v-deep(.capture-selector) {

  .s-list {
    overflow: hidden;

    .s-item {

      border-bottom: 1px solid #e5f1fc;
      text-align: center;
      position: relative;

      .item__btn {
        height: 100%;
        width: 100%;
        display: inline-block;
        padding: 22rpx 0rpx;
      }
    }
  }
}

.inside__input {
  ::v-deep.uni-numbox__value {
    height: 21px !important;
  }

  ::v-deep.uni-select {
    height: 21px !important;
  }
}
</style>
